package org.devgframwork.datasync.admin.support.init.schedule;

import com.alibaba.fastjson.JSONObject;
import org.devgframwork.datasync.core.entity.ScheduleConfig;
import org.devgframwork.datasync.core.model.ExecutorModel;
import org.devgframwork.datasync.core.model.ResultModel;
import org.devgframwork.datasync.core.support.executors.AbstractProxyExecutor;
import org.devgframwork.datasync.core.support.service.ScheduleConfigService;
import org.devgframwork.datasync.core.utils.CommonUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ScheduleRunnable implements Runnable {

    private ScheduleConfig scheduleConfig;

    private ScheduleConfigService scheduleConfigService;

    public ScheduleRunnable(ScheduleConfig scheduleConfig, ScheduleConfigService scheduleConfigService) {
        this.scheduleConfig = scheduleConfig;
        this.scheduleConfigService = scheduleConfigService;
    }

    @Override
    public void run() {
        this.scheduleConfig = scheduleConfigService.getById(scheduleConfig.getScheduleConfigId());
        if (!check(scheduleConfig)) {
            return;
        }
        long t1 = System.currentTimeMillis();
        log.info("invoke task:{},now:{}", scheduleConfig.getTaskName(), t1);
        try {
            ExecutorModel executorModel = new ExecutorModel(CommonUtil.dataSyncAll, scheduleConfig.getTaskName());
            AbstractProxyExecutor abstractProxyExecutor = new AbstractProxyExecutor(executorModel);
            ResultModel resultModel = abstractProxyExecutor.invoke();
            log.info("invoke task:{},result:{}", scheduleConfig.getTaskName(), JSONObject.toJSONString(resultModel));
//            MessageService.sendRabbitMqMessage(scheduleConfig.getConnectionName(), CommonUtil.dataSyncAll, scheduleConfig.getTaskName());
        } catch (Exception ex) {
            log.error("run schedule:" + scheduleConfig.getScheduleConfigId() + " error", ex);
        }
    }

    private boolean check(ScheduleConfig scheduleConfig) {
        String taskName = scheduleConfig.getTaskName();
        String sourceKey = scheduleConfig.getSourceKey();
        if (CommonUtil.isEmpty(sourceKey)) {
            log.error("taskName:" + taskName + ",sourceKey can not be empty!");
            return false;
        }
        return true;
    }


}
